import { Command } from 'commander'
import { git } from './git/git'
import { br } from './branches'

export function autoCommit(content: string) {
  if (content.startsWith('[version]')) {
    br.autoCommitAtCurrentBranch(content)
    return
  }

  // 标记提交动作
  let commitType = '[modify]'
  if (content.startsWith('添加')) {
    commitType = '[add]'
  } else if (content.startsWith('删除')) {
    commitType = '[delete]'
  } else if (content.startsWith('重构')) {
    commitType = '[refactor]'
  } else if (content.startsWith('修复')) {
    commitType = '[fix]'
  }

  br.autoCommitAtCurrentBranch(commitType + ' ' + content)
}

function addPrefix(prefix: string, content: string) {
  if (content.startsWith(prefix + '/')) return content;
  return `${prefix}/${content}`
}

export function cmContent(program: Command) {
  function commit(msg: string) {
    br.autoCommitAtCurrentBranch(msg)
  }
  function makeCommitType(type: string) {
    program
      .command(type)
      .description(`[${type}] 提交`)
      .argument('<content...>', '提交的内容')
      .action((content: string[], opt) => {
        // 默认提交 fix commit
        commit(`[${type}] ${content.join(' ')}`)
        return
      })
  }

  makeCommitType('fix')
  makeCommitType('delete')
  makeCommitType('modify')
  makeCommitType('add')
  makeCommitType('refactor')
  makeCommitType('dev')

  program
    .argument(
      '[content...]',
      '需要提交的内容, 如果检测到是一个分支名则尝试创建这个分支',
    )
    .option('-1', '回退一次提交')
    .option('-f, --force', '是否强制切换到目标分支')
    .option('-b, --base', '从哪个分支切出来的')
    .option('-w, --week', '周版本分支')
    .action((contentArg: string[], opt) => {
      if (!contentArg.length) {
        console.log('...')
        return
      }

      // 回退一个提交
      if (opt['1']) {
        // -1
        git.reset()
        return
      }

      let content = contentArg.join(' ')
      let newBranchPrefix = '';

      // 从周版本分支创建功能开发分支
      if (opt.week) {
        const currentBranch = br.currentBranch
        const prefix = currentBranch.split('/')[0]
        
        if (!prefix) {
          console.log('错误: 无法从当前分支提取前缀')
          return
        }

        const weekBranch = `${prefix}/周版本分支`
        newBranchPrefix = prefix;

        console.log(`切换到周版本分支: ${weekBranch}`)
        git.gotoTarget(weekBranch)
      }

      // 创建提单分支
      if (content.match(/^[0-9]+\s/)) {
        console.log(content)
        const res = content.match(/^([0-9]+)[\s]+(.*)$/)
        if (res) {
          const taskNo = res[1]
          const content = addPrefix(newBranchPrefix, res[2])
          const contentIsBranch = content.split('/').length > 1
          if (contentIsBranch) {
            const branchDir = content.split('/')[0]
            const branchName = content.split('/')[1]
            br.checkoutBranch(`${branchDir}/refs#${taskNo}-${branchName}`, opt.force)
            return
          }
          br.checkoutBranch(`feature/refs#${taskNo}-${content}`, opt.force)
          return
        }
      }

      // 创建分支
      const branchMatched = content.includes('/')
      if (branchMatched) {
        if (content.startsWith('/')) {
          content = content.slice(1)
        }
        else if (content.startsWith('./')) {
          content = content.slice(2)
        }

        br.checkoutBranch(content, opt.force)
        return
      }

      // 自动提交
      autoCommit(content)
    })
}
